package _543cloud_new;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;


public class MultiHelper {

	Graph_Multi m_graph;
	public Set<Match_Multi> matchs = new HashSet<Match_Multi>();
	Calculator calcal = new Calculator();
	static int MAXVALUE = 1<<20;
	//lnodes,rnodes
	HashMap<String,Left_node> m_lnodes = new HashMap<>();
	HashMap<String,Right_node> m_rnodes = new HashMap<>();
		
	public MultiHelper() throws IOException{
		m_graph = new Graph_Multi();
		m_lnodes = m_graph.lnodes;
		m_rnodes = m_graph.rnodes;
		run();
	}
	
	public void delete_neighbor(Left_node input_l, ArrayList<Right_node> input_r){
		m_lnodes.remove(input_l.name);
		for(int i=0;i<input_r.size();i++){
			m_rnodes.remove(input_r.get(i).name);
		}
	}
	
	public void run(){
		while(!m_graph.l_queue.isEmpty()){
			Left_node l_temp = m_graph.l_queue.poll();
			ArrayList<Right_node> l_res = chose(l_temp);
			if(l_res == null) continue;
			delete_neighbor(l_temp, l_res);
			Match_Multi temp_match = new Match_Multi();
			for(int i=0;i<l_res.size();++i){
				temp_match.addup(l_temp.name,l_res.get(i).name);
			}
			matchs.add(temp_match);
		}
	}
	

	public ArrayList<Right_node> chose(Left_node ln){
		
		Iterator<Right_node> temp_i = ln.neighbor_queue.iterator();
		int sum = 0;int flag = 0;
		// int[] capacity = new int[ln.neighbor_queue.size()];
		ArrayList<Integer> capacity = new ArrayList<>();
		//Hashmap<Index, Right_node>
		HashMap<Integer,Right_node> index_rnode = new HashMap<>();

		while(temp_i.hasNext()){
			Right_node tempr = temp_i.next();
			if(m_graph.rnodes.containsKey(tempr.name)){
				capacity.add(tempr.cap);
				sum+=tempr.cap;
				index_rnode.put(flag++,tempr);
			}

		}
		if(ln.cap>sum) return null;
		int[] cap_array = new int[capacity.size()];
		for(int i=0;i<capacity.size();i++)
			cap_array[i]=capacity.get(i);
		
		int[] result = (new Calculator(cap_array,ln.cap)).getresult();
		ArrayList<Right_node> to_return = new ArrayList<>();
		for(int i=0;i<result.length;++i){
			to_return.add(index_rnode.get(result[i]));
		}
	
		return to_return;
	}

	public void printresult(){
		System.out.println(matchs);
	}
	
	public static void main(String[] args) throws IOException {
		MultiHelper testHelper = new MultiHelper();
		System.out.println("The result of multi-helper is:");
		testHelper.printresult();
	}

}
